import React, { Component } from 'react';
import moment from 'moment'
import { connect } from 'react-redux'  
import { Modal, Form, Input,Select ,DatePicker,message,TimePicker,Radio,Button,Row,Icon, Col,TreeSelect} from 'antd';
const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const RadioGroup = Radio.Group;
const Option =Select.Option;
const TreeNode = TreeSelect.TreeNode;
var dayList = ['1', '2','3', '4','5', '6','7', '8','9', '10','11', '12','13', '14','15', '16','17', '18','19', '20','21', '22','23', '24','25', '26','27', '28','29', '30','31'];

class AddModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
  }

  okHandler = () => {
     const { onOk,cycletime,condition,isShowTime } = this.props;
     this.props.form.validateFields((err, values) => {      
      if (!err) {
        if(values.statisticsCondition!=null&&values.statisticsCondition.length>0){
          if(JSON.stringify(condition)=="{}"){
            message.error('请选择列表参数');
            return ;
          }
          if(isShowTime==2){
            values = {
              ...values,
              statisticsCondition:values.statisticsCondition.toString(),
              condition:JSON.stringify(condition),
            }
            onOk(values);
          }else{
            var list = [];
            cycletime.reportPlanList.map(d=>{
              var dr = {
                ...d,
              };
              if(dr.time){
                dr.time = new moment(dr.time).format("HH:mm");
                list.push(dr);
              }  
            })
            
            if(list!=null&&list.length>0){ 
              values = {
                ...values,
                statisticsCondition:values.statisticsCondition.toString(),
                condition:JSON.stringify(condition),
                cycleType:cycletime.cycleType,
                reportPlanList: list,
              }
              console.log(values);
              onOk(values);
            }else{
              message.error('请选择执行时间');
          }
          }         
        }else{
          message.error('请选择统计参数');
        } 
      }
     });
  };
  
  render() {
    const { children, dispatch,item,cycletime,condition,isShow,isShowTime,assetTypeTree,roomList,assetBrandList,assetModelList,rackList,manageDeptTree,useDeptTree,userList,
      typeId,brandId} = this.props;  
    const { getFieldDecorator } = this.props.form;   
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    };  

    const formItemLayout1 = {
      labelCol: { span: 3 },
      wrapperCol: { span: 20 },
    };     
       
    const getDay = data => data.map((item) => {
      return <Option key={item+''}>{item}日</Option>
     })
     const cycletimeChange = function(e){
       dispatch({
         type: "reportPlan/upState",
         payload: {
           cycletime: {
            reportPlanList: [],
            cycleType: e.target.value,
           }
         }
       })
     }

     const typeChange = function(e){
      dispatch({
        type: "reportPlan/upState",
        payload: {
            isShowTime:e.target.value,
            cycletime:{ cycleType: 1, reportPlanList:[],},
          }
      })
    }

     const addIns = () => {
       cycletime.reportPlanList.push({})
       dispatch({
         type: "reportPlan/upState",
         payload: {
           cycletime: cycletime,
         }
       })
     }
     const delIns = (ind) => {
       cycletime.reportPlanList.splice(ind,1);
       dispatch({
         type: "reportPlan/upState",
         payload: {
           cycletime: cycletime,
         }
       })
     }
     const changeIns = (value,ind,name) => {
       cycletime.reportPlanList[ind][name] = value;
       dispatch({
         type: "reportPlan/upState",
         payload: {
           cycletime: cycletime,
         }
       })
     }
     const showIns = data => {
       switch(data.cycleType){
         case 1:
          return data.reportPlanList.map((item,index) => (
           <div key={index}>
             <div style={{float:"left",marginRight:30}}>
                <TimePicker format="HH:mm" value={item.time} onChange={(e)=>changeIns(e,index,"time")} style={{width:'110px'}}/></div>
             <div style={{float:"left"}}><Button type="danger" onClick={()=>delIns(index)}>删除</Button></div>
             <div style={{display:"block",height:0,clear:"both"}}></div>
           </div>
          ));
         case 2:
          return data.reportPlanList.map((item,index) => (
           <div key={index}>
             <div style={{float:"left",marginRight:30}}>
               <Select value={item.day!=null?item.day+'':undefined} placeholder="选择时间" onChange={(e)=>changeIns(e,index,"day")} style={{ width: 80 }} >
                 <Option value="1">周一</Option>
                 <Option value="2">周二</Option>
                 <Option value="3">周三</Option>
                 <Option value="4">周四</Option>
                 <Option value="5">周五</Option>
                 <Option value="6">周六</Option>
                 <Option value="7">周日</Option>
               </Select> 
             </div>
             <div style={{float:"left",marginRight:30}}>
                <TimePicker format="HH:mm" value={item.time} onChange={(e)=>changeIns(e,index,"time")} style={{width:'110px'}}/></div>
             <div style={{float:"left"}}><Button  type="danger" onClick={()=>delIns(index)}>删除</Button></div>
             <div style={{display:"block",height:0,clear:"both"}}></div>
           </div>
          ));
         case 3:
          return data.reportPlanList.map((item,index) => (
           <div key={index}>
             <div style={{float:"left",marginRight:30}}>
               <Select value={item.day!=null?item.day+'':undefined} placeholder="选择日期" onChange={(e)=>changeIns(e,index,"day")} style={{ width: 80 }} >        
                  {getDay(dayList)}                       
               </Select>
             </div>
             <div style={{float:"left",marginRight:20}}>
               <TimePicker format="HH:mm" value={item.time} onChange={(e)=>changeIns(e,index,"time")} style={{width:'110px'}}/></div>
             <div style={{float:"left"}}><Button  type="danger" onClick={()=>delIns(index)}>删除</Button></div>
             <div style={{display:"block",height:0,clear:"both"}}></div>
           </div>
          ));
       }
     }

    const changeCondition = (value,name) => {
      if(name=="room_id"){
        dispatch({
          type: "reportPlan/qryRackList",
          payload:value
        })
      }else if(name=="brand_id"){
        dispatch({
          type: "reportPlan/queryAssetModel",
          payload:{typeId:typeId,brandId:value}
        })
      }else if(name=="type_id"){
        dispatch({
          type: "reportPlan/queryAssetModel",
          payload:{typeId:value,brandId:brandId}
        })
      }else if(name=="use_branch_id"){
        dispatch({
          type: "reportPlan/qryUserByDept",
          payload:{deptId:value },
        })
      }
      condition[name] = value;
      dispatch({
        type: "reportPlan/upState",
        payload: {
          condition: condition,
        }
      })
    }
    const valueChangeCondition = (value,name) => {
      condition[name] = value.target.value;
      dispatch({
        type: "reportPlan/upState",
        payload: {
          condition: condition,
        }
      })
    }   
    const toggle = () => {
      dispatch({
        type: "reportPlan/upState",
        payload: {
          isShow: !isShow,
        }
      })
    }
    const getBrand = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.name}</Option>
    })
    const getModel = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.name}</Option>
    })
    const getRoom = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.name}</Option>
    })
    const getRack = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.assetName}</Option>
    })
    const getUser = data => data.map((item) => {
      return <Option key={item.id_+''}>{item.name}</Option>
    })
    const loop = data => data.map((item) => {
      if (item.assetType && item.assetType.length) {
        return <TreeNode key={item.id_+''} title={item.name} value={item.id_+''}>{loop(item.assetType)}</TreeNode>;
      }
      return <TreeNode key={item.id_+''} title={item.name} value={item.id_+''} />;
    });
    const treeData = (i) => {
      return i.map( d => {
        d.label = d.name;
        d.key = d.id_+'';
        d.value = d.id_+'';
        d.children = d.depts && d.depts.length > 0 ? treeData(d.depts) : [];
        return d;
      })
    }

    const showConditionIns = () => {
      return <div>
               <div style={{width:'50%',float:"left",}}>
                <div style={{float:"left",marginRight:5}}>所在机房： </div>
                <div style={{float:"left",marginRight:5}}>
                  <Select  placeholder="请选择所在机房" onChange={(e)=>changeCondition(e,"room_id")} style={{ width:'200px' }} >
                    {getRoom(roomList)}        
                  </Select>                 
                </div> 
                <div style={{display:"block",height:0,clear:"both"}}></div>
              </div> 
              <div style={{width:'50%',float:"right",}}>
                <div style={{float:"left",marginRight:5}}>所在机柜： </div>
                <div style={{float:"left",marginRight:5}}>
                  <Select  placeholder="请选择所在机柜" onChange={(e)=>changeCondition(e,"rack_id")} style={{ width:'200px' }} >
                    {getRack(rackList)}        
                  </Select> 
                </div>  
                <div style={{display:"block",height:0,clear:"both"}}></div> 
              </div>   
              <div style={{width:'50%',float:"left",}}>
                <div style={{float:"left",marginRight:5}}>资产sn号： </div>
                <div style={{float:"left",marginRight:5}}>
                  <Input onChange={(e)=>valueChangeCondition(e,"serial_no")} placeholder="请输入资产序列号模糊查询"  style={{width:'200px'}}/>
                </div> 
                <div style={{display:"block",height:0,clear:"both"}}></div>
              </div> 
              <div style={{width:'50%',float:"left",}}>
                <div style={{float:"left",marginRight:5}}>资产RFID：</div>
                <div style={{float:"left",marginRight:5}}>
                  <Input onChange={(e)=>valueChangeCondition(e,"rfid_no")} placeholder="请输入RFID号模糊查询"  style={{width:'200px'}}/>
                </div> 
                <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>  
              <div style={{width:'50%',float:"left",}}>
                <div style={{float:"left",marginRight:5}}>资产编号：</div>                
                <div style={{float:"left",marginRight:5}}>
                    <Input onChange={(e)=>valueChangeCondition(e,"asset_no")} placeholder="请输入资产编号模糊查询"  style={{width:'200px'}}/>
                </div> 
              </div>
              <div style={{width:'50%',float:"left",}}>
                <div style={{float:"left",marginRight:5}}>资产名称：</div>
                <div style={{float:"left",marginRight:5}}>
                  <Input onChange={(e)=>valueChangeCondition(e,"asset_name")} placeholder="请输入资产名称模糊查询"  style={{width:'200px'}}/>
                </div>
              </div>
             {isShow==true?(<div>
              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5}}>资产分类：</div>
              <div style={{float:"left",marginRight:5}}>
                 <TreeSelect
                      showSearch
                      treeNodeFilterProp="title"
                      notFoundContent="无匹配结果"
                      style={{ width:'200px' }}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      placeholder="请选择资产分类"
                      allowClear
                      onChange={(e)=>changeCondition(e,"type_id")}
                      treeDefaultExpandAll
                    >
                     { assetTypeTree.assetType && loop(assetTypeTree.assetType) }
                 </TreeSelect>
              </div> 
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5}}>资产品牌：</div>
              <div style={{float:"left",marginRight:5}}>
                <Select  placeholder="请选择资产品牌" onChange={(e)=>changeCondition(e,"brand_id")} style={{ width:'200px' }} >
                 {getBrand(assetBrandList)}
               </Select> 
              </div>  
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5}}>资产型号：</div>
              <div style={{float:"left",marginRight:5}}>
                <Select  placeholder="请选择资产型号" onChange={(e)=>changeCondition(e,"model_id")} style={{ width:'200px' }} >
                  {getModel(assetModelList)}
               </Select> 
              </div>  
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>             

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5}}>资产状态：</div>
              <div style={{float:"left",marginRight:5}}>
                <Select  placeholder="请选择资产状态" onChange={(e)=>changeCondition(e,"status_")} style={{ width:'200px' }} >
                 <Option value="1">已入库</Option>
                 <Option value="2">在架</Option>
                 <Option value="3">已报废</Option>
                 <Option value="4">已出库</Option>
               </Select> 
              </div>  
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5}}>购置时间： </div>
              <div style={{float:"left",marginRight:5}}>
                 <RangePicker onChange={(e)=>changeCondition(e,"buy_time")} placeholder={['开始时间', '结束时间']} style={{ width: '200px' }}  format="YYYY-MM-DD" />
              </div> 
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5}}>维保时间：</div>
              <div style={{float:"left",marginRight:5}}>
                   <RangePicker onChange={(e)=>changeCondition(e,"expiration_time")} placeholder={['开始时间', '结束时间']} style={{ width: '200px' }}  format="YYYY-MM-DD" />
              </div> 
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5, letterSpacing:'0.3em'}}>IP地址：</div>
              <div style={{float:"left",marginRight:5}}>
                <Input onChange={(e)=>valueChangeCondition(e,"ip")} placeholder="请输入IP模糊查询"  style={{width:'196px'}}/>
              </div> 
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5}}>管理部门：</div>
              <div style={{float:"left",marginRight:5}}>               
               <TreeSelect
                  showSearch
                  treeNodeFilterProp="title"
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder="请选择管理部门"
                  allowClear
                  style={{ width:'200px' }}
                  onChange={(e)=>changeCondition(e,"manage_branch_id")} 
                  treeData={treeData(manageDeptTree)}
                  treeDefaultExpandAll
                >                            
                </TreeSelect>
              </div>  
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5}}>使用部门：</div>
              <div style={{float:"left",marginRight:5}}>             
               <TreeSelect
                  showSearch
                  treeNodeFilterProp="title"
                  dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                  placeholder="请选择使用部门"
                  allowClear
                  treeData={treeData(useDeptTree)}
                  onChange={(e)=>changeCondition(e,"use_branch_id")} 
                  style={{ width:'200px' }} 
                  treeDefaultExpandAll
                >                            
                </TreeSelect>
              </div>  
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5,letterSpacing:'0.3em'}}>使用人：</div>
              <div style={{float:"left",marginRight:5}}>
                <Select  placeholder="请选择使用人" onChange={(e)=>changeCondition(e,"end_user")} style={{ width:'200px' }} >
                  {getUser(userList)}
                </Select> 
              </div>  
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5,letterSpacing:'0.3em'}}>合同号：</div>
              <div style={{float:"left",marginRight:5}}>
                 <Input onChange={(e)=>valueChangeCondition(e,"contract_no")} placeholder="请输入合同号模糊查询"  style={{width:'200px'}}/>
              </div> 
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5,letterSpacing:'0.3em'}}>发票号：</div>
              <div style={{float:"left",marginRight:5}}>
                 <Input onChange={(e)=>valueChangeCondition(e,"invoice_no")} placeholder="请输入发票号模糊查询"  style={{width:'200px'}}/>
              </div> 
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5,letterSpacing:'0.3em'}}>供货方：</div>
              <div style={{float:"left",marginRight:5}}>
                 <Input onChange={(e)=>valueChangeCondition(e,"supplier_")} placeholder="请输入供货方模糊查询"  style={{width:'198px'}}/>
              </div> 
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5}}>联系电话：</div>
              <div style={{float:"left",marginRight:5}}>
                 <Input onChange={(e)=>valueChangeCondition(e,"contacts_phone")} placeholder="请输入供货方联系电话模糊查询"  style={{width:'200px'}}/>
              </div> 
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5,letterSpacing:'0.3em'}}>联系人：</div>
              <div style={{float:"left",marginRight:5}}>
                 <Input onChange={(e)=>valueChangeCondition(e,"contacts_")} placeholder="请输入供货方联系人模糊查询"  style={{width:'200px'}}/>
              </div> 
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>    

              <div style={{width:'50%',float:"left",}}>
              <div style={{float:"left",marginRight:5}}>售后电话：</div>
              <div style={{float:"left",marginRight:5}}>
                 <Input onChange={(e)=>valueChangeCondition(e,"hotline")} placeholder="请输入售后电话模糊查询"  style={{width:'200px'}}/>
              </div> 
              <div style={{display:"block",height:0,clear:"both"}}></div>
              </div>  

          </div>):null} 
          <a style={{ marginLeft: 8, fontSize: 12 }} onClick={toggle}>
          {isShow ? '收起' : '展开'} <Icon type={isShow ? 'up' : 'down'} />
          </a>
    </div>

    }

    return (
      <span>
            <Modal
              maskClosable= {this.props.maskClosable}
              confirmLoading= {this.props.confirmLoading}
              title={this.props.title}
              width={700}
              visible={this.props.visible}
              onOk={this.okHandler}
              onCancel={this.props.onCancel}
              key={this.props.newKey}
            >
              <Form layout='horizontal' onSubmit={this.okHandler}>
                    <FormItem style={{marginBottom:'0px'}}>
                      {getFieldDecorator('id',{initialValue:item.id_})(
                        <Input type="hidden"/>
                      )}
                    </FormItem>       
                    <Row>           
                      <Col span={12}>    
                        <FormItem
                            {...formItemLayout}
                              label="模板名称"
                              hasFeedback
                            >
                            {
                              getFieldDecorator('name', {
                                initialValue: item.name,
                                rules: [{
                                  required: true, whitespace: true, message: '请输入模板名称',
                                },{
                                  max:20,message: '模板名称不能超过20个字',
                                }]
                              })(<Input  placeholder="请输入模板名称" />)
                            }
                        </FormItem>  
                      </Col>
                      <Col span={12}>   
                        <FormItem
                            {...formItemLayout}
                              label="报表类型"   
                              required
                              hasFeedback
                            >
                            {getFieldDecorator('type', {
                              initialValue:  item.type == null? 2 : item.type,                            
                            })(
                              <RadioGroup onChange={typeChange}>                                
                                <Radio value={2}>手动</Radio>
                                <Radio value={1}>自动</Radio>
                              </RadioGroup>
                              )}
                        </FormItem>  
                      </Col>
                      </Row>
                      {isShowTime==1?(<Row>
                        <Col span={24}>
                          <FormItem
                            {...formItemLayout1}                        
                            required
                            label="重复周期"
                            >
                                <RadioGroup value={cycletime.cycleType} onChange={cycletimeChange}>
                                  <Radio value={1}>每天</Radio>
                                  <Radio value={2}>每周</Radio>
                                  <Radio value={3}>每月</Radio>
                                </RadioGroup>
                          </FormItem>  
                        </Col>                        
                      </Row>):null}
                      {isShowTime==1?(<Row>
                        <Col span={24}>
                          <FormItem
                            {...formItemLayout1}
                            label="执行时间"                            
                            required
                            >  
                            <div style={{marginBottom:10}}>
                              <Button type="primary" size="large" onClick={addIns}>添加时间</Button>
                            </div>
                            {showIns(cycletime)}
                          </FormItem> 
                        </Col>
                      </Row>):null}
                     
                      <Row>                       
                        <Col span={24}> 
                          <FormItem 
                            {...formItemLayout1}
                            label="统计参数"
                            required                              
                            hasFeedback
                          >
                          {getFieldDecorator('statisticsCondition')(
                            <Select
                              showSearch
                              mode="multiple"
                              placeholder="选择统计参数"
                              optionFilterProp="children"
                            >
                              <Option value="资产分类">资产分类</Option>
                              <Option value="资产品牌">资产品牌</Option>
                              <Option value="资产型号">资产型号</Option>
                              <Option value="机房">机房</Option>
                              <Option value="购置时间">购置时间</Option>
                              <Option value="维保到期时间">维保到期时间</Option>
                              <Option value="管理部门">管理部门</Option>
                              <Option value="使用部门">使用部门</Option>
                          </Select>
                        )}
                        </FormItem>    
                      </Col>
                      </Row>

                      <Row>
                        <Col span={24}>
                          <FormItem 
                              {...formItemLayout1}
                              label="列表参数"
                              required                              
                              hasFeedback
                            >
                            {/* <div style={{marginBottom:10}}>
                              <Button type="primary" size="large" onClick={addCondition}>添加列表参数</Button>
                            </div> */}
                            {showConditionIns()}
                          </FormItem>  
                      </Col>
                      </Row>
                      <Row>
                      <Col span={24}>
                        <FormItem
                            {...formItemLayout1}
                            label="备注"
                            hasFeedback
                        >
                        {
                          getFieldDecorator('remark', {
                            initialValue:  item.remark,  
                            rules: [{ max: 200, message: '备注信息 200 字符以内' },]
                          })(<Input type="textarea" autosize={{ minRows: 3, maxRows: 6 }}/>)
                        }
                      </FormItem>
                     </Col>
                   </Row>
                </Form>              
        </Modal>        
      </span>
    );
  }
    
}

export default Form.create()(AddModal)